package com.example.filter;

import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@WebFilter("/*") // 这里指定拦截所有请求

public class MyFilter implements Filter {

    @Value("${print.file.requestFile}")
    private String requestInfoPath;

    @Override
    public void init(FilterConfig filterConfig) {

        /**
         * 判断当前文件夹是否存在，若是不存在则创建
         */
        checkRequestInfoPathExits(requestInfoPath);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        /**
         * 该方法用于记录所有的请求访问日志
         * 对应配置文件中的print.file.chatFile：的value
         * ，Filter是javaWEB提供的，不是Spring框架中的，所以执行要在interceptor之前
         */
        RecordLog((HttpServletRequest) servletRequest);

        filterChain.doFilter(servletRequest, servletResponse);                      // 继续处理请求链

    }
    public void checkRequestInfoPathExits(String filePath) {
        File file = new File(filePath);
        String parentFolderPath = file.getParent();
        File parentFolder = new File(parentFolderPath);
        boolean created = parentFolder.mkdirs();                        // 使用mkdirs()以确保创建多层文件夹

        if (created) {
            log.info("创建完毕！");
        }
    }
    private void RecordLog(HttpServletRequest servletRequest) {
        HttpServletRequest httpRequest = servletRequest;
        String requestURL = String.valueOf(httpRequest.getRequestURL());            //获取请求的URL，包含协议，主机名端口，URI
        String method = httpRequest.getMethod();                                    //获取请求的方式
        String locale = String.valueOf(httpRequest.getLocale());
        String ipAddress = httpRequest.getRemoteAddr();                             // 获取请求的IP地址
        String hostName = httpRequest.getRemoteHost();                              // 获取请求的主机名
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");           // 格式化日期时间和毫秒
        String formattedDateTime = now.format(formatter);


        String jwt = httpRequest.getHeader("token");
        Integer id = null;
        String studentID = "null    ";
        String name = "null  ";
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(jwt);
            id = (Integer)claims.get("id");
            studentID = (String) claims.get("studentID");
            name = (String) claims.get("name");
        }catch (Exception e){

            log.error("token为空~~~，Filter异常！");
            log.error("token为空~~~，Filter异常！");
        }

        try (
                PrintStream ps = new PrintStream(new FileOutputStream(requestInfoPath, true))
                ){
                String requestInfo = new StringBuilder().append("请求信息  --->>>  ")
                        .append("请求时间：").append(formattedDateTime).append("  ")
                        .append("主键id：").append(String.valueOf(id)).append("  ")
                        .append("学号studentID：").append(studentID).append("  ")
                        .append("姓名name：").append(name).append("  ")
                        .append("请求地址requestURL：").append(requestURL).append("  ")
                        .append("请求方式method：").append(method).append("  ")
                        .append("请求IPipAddress").append(ipAddress).append("  ")
                        .append("请求主机名hostName").append(hostName).append("  ")
                        .append("语言locale：").append(locale).toString();
                ps.println(requestInfo);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
